package org.jeecg.modules.bicycle.vehicle.controller;

import java.io.IOException;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.sql.visitor.functions.If;
import com.xkcoding.http.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.ini4j.spi.RegEscapeTool;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bicycle.vehicle.entity.BikeVehicle;
import org.jeecg.modules.bicycle.vehicle.service.IBikeVehicleService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.bicycle.vehicle.vo.BikeCard;
import org.jeecg.modules.bicycle.vehicle.vo.BikeVehicleInitialization;
import org.jeecg.modules.bicycle.vehicle.vo.GetBikeCode;
import org.jeecg.modules.bicycle.vehicle.vo.SmsParam;
import org.jeecg.modules.common.service.CommonMethodService;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.system.allsmslog.entity.BikeSysSmsLog;
import org.jeecg.modules.system.allsmslog.service.BikeSysSmsLogService;
import org.jeecg.modules.utils.*;
import org.jeecg.modules.utils.page.PageInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 车辆管理
 * @Author: 月月鸟
 * @Date: 2021-05-19
 * @Version: V1.0
 */
@Api(tags = "车辆管理")
@RestController
@RequestMapping("/vehicle/bikeVehicle")
@Slf4j
public class BikeVehicleController extends JeecgController<BikeVehicle, IBikeVehicleService> {
    @Autowired
    private IBikeVehicleService bikeVehicleService;
    @Autowired
    private CommonMethodService commonMethodService;

    @Autowired
    private BikeSysSmsLogService bikeSysSmsLogService;
    /**
     * 分页列表查询
     *
     * @param bikeVehicle
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "车辆管理-分页列表查询", notes = "车辆管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(BikeVehicle bikeVehicle,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if (StringUtils.isNotEmpty(bikeVehicle.getStationId())) {
            List<String> childStation = commonMethodService.getChildStation(bikeVehicle.getStationId());
            if (!childStation.isEmpty()) {
                bikeVehicle.setStationArray(childStation);
            } else {
                return Result.OK();
            }
        }
        Page<BikeVehicle> page = new Page<>(pageNo, pageSize);
        Page<BikeVehicle> pageList = bikeVehicleService.pageList(page, bikeVehicle);
        PageInfo pageInfo = new PageInfo();
        pageInfo.setRecords(pageList.getRecords());
        pageInfo.setTotal(pageList.getTotal());
        pageInfo.setSize(pageList.getSize());
        pageInfo.setCurrent(pageList.getCurrent());
        return Result.OK(pageInfo);
    }


    /**
     * 根据code查电动车
     *
     * @param code
     * @return
     */
    @ApiOperation(value = "根据code查电动车", notes = "根据code查电动车")
    @GetMapping(value = "/getByCode")
    public Result<?> getByCode(@RequestParam(required = false) String code) {

        return bikeVehicleService.getByCode(code);
    }

    /**
     * 添加
     *
     * @param bikeVehicle
     * @return
     */
    @AutoLog(value = "车辆管理-添加",operateType = 2)
    @ApiOperation(value = "车辆管理-添加", notes = "车辆管理-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BikeVehicle bikeVehicle) {
        String code = bikeVehicle.getCode();
        QueryWrapper<BikeVehicle> bikeVehicleQueryWrapper = new QueryWrapper<>();
        bikeVehicleQueryWrapper.eq("code", code);
        List<BikeVehicle> list = bikeVehicleService.list(bikeVehicleQueryWrapper);
        if (list.isEmpty()) {
            bikeVehicleService.save(bikeVehicle);
            return Result.OK("添加成功！");
        } else {
            return Result.error("编号重复！");
        }
    }

    public static void main(String[] args) {
        String s = EstUtils.hexAddCrc8ToAscii("F8A6ACEAE964E31F6CA56927A8C7C2");
        System.out.println(s);
    }
    /**
     * 读卡查询
     *
     * @param bikeVehicle
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "车辆管理-读卡查询", notes = "车辆管理-读卡查询")
    @GetMapping(value = "/readCardList")
    public Result<?> readCardList(BikeVehicle bikeVehicle,
                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                  HttpServletRequest req) {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(pageNo);
        pageInfo.setTotal(0);
        List<BikeVehicle> list1 = new ArrayList<>();
        pageInfo.setRecords(list1);
        String code = bikeVehicle.getCode();
        String s = EstUtils.hexAddCrc8ToAscii(bikeVehicle.getCode());
        if (StringUtils.isNotEmpty(s)) {
            bikeVehicle.setCode(s);
        } else {
            return Result.OK(pageInfo);
        }
        Page<BikeVehicle> page = new Page<>(pageNo, pageSize);
        Page<BikeVehicle> bikeVehiclePage = bikeVehicleService.pageList(page,bikeVehicle);
        List<BikeVehicle> list = bikeVehiclePage.getRecords();
        for (BikeVehicle tb : list ){
            String s1 = EstUtils.asciiToHexAddCrc8(tb.getCode());
            if (!code.equals(s1.toUpperCase())){
                tb.setCheckBikeCRC(BikeConstant.y_n_yes);
            }else {
                tb.setCheckBikeCRC(BikeConstant.y_n_no);
            }
        }
        pageInfo.setRecords(bikeVehiclePage.getRecords());
        pageInfo.setTotal(bikeVehiclePage.getTotal());
        pageInfo.setSize(bikeVehiclePage.getSize());
        pageInfo.setCurrent(bikeVehiclePage.getCurrent());
        return Result.OK(pageInfo);
    }

    /**
     * 发卡校验
     *
     * @param bikeVehicle
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "车辆管理-发卡校验", notes = "车辆管理-发卡校验")
    @GetMapping(value = "/checkCardList")
    public Result<?> checkCardList(BikeVehicle bikeVehicle,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        if (StringUtils.isNotEmpty(bikeVehicle.getCode())) {
            String code = EstUtils.hexAddCrc8ToAscii(bikeVehicle.getCode());
            boolean b = bikeVehicleService.checkCode(code);
            if (b) {
                return Result.OK();
            } else {
                return Result.error("此卡已绑定，请更换卡片");
            }
        }
        return Result.OK();
    }


    /**
     * 换卡校验
     *
     * @param bikeVehicle
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "车辆管理-换卡校验", notes = "车辆管理-换卡校验")
    @GetMapping(value = "/checkChangeCardList")
    public Result<?> checkChangeCardList(BikeVehicle bikeVehicle,
                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         HttpServletRequest req) {
        if (StringUtils.isNotEmpty(bikeVehicle.getCode())) {
            String code = EstUtils.hexAddCrc8ToAscii(bikeVehicle.getCode());
            boolean b = bikeVehicleService.checkCode(code);
            if (b) {
                return Result.OK();
            } else {
                return Result.error("此卡已绑定，请更换卡片");
            }
        }
        return Result.OK();
    }

    /**
     * 批量发卡-查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "车辆管理-批量发卡", notes = "车辆管理-批量发卡")
    @GetMapping(value = "/sendCardBatch")
    public Result<?> sendCardBatch(@RequestParam(name = "id", required = true) String id) {
        QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
        wrapper.eq("is_register", BikeConstant.y_n_no);
        List<BikeVehicle> list = bikeVehicleService.list();
        YueYueNiaoUtils.deleteFrontDataById(list, id);
        return Result.OK("批量成功!");
    }

    /**
     * 转hex
     *
     * @return
     */
    @ApiOperation(value = "车辆管理-转hex", notes = "车辆管理-转hex")
    @DeleteMapping(value = "/goHex")
    public Result<?> checkCardList(@RequestParam(name = "code", required = true) String code) {
        String s = EstUtils.asciiToHexAddCrc8(code);
        return Result.OK(s);
    }
    @ApiOperation(value = "车辆管理-测试用 获取异常加密车辆", notes = "车辆管理-测试用 获取异常加密车辆")
    @GetMapping(value = "/getErrBike")
    public List<String> getErrBike(){
        List<BikeVehicle> list = bikeVehicleService.list();
        List<String> arrayList = new ArrayList<>();
        List<BikeVehicle> bikeVehicleList = new ArrayList<>();
        for (BikeVehicle tb : list){
            String str = tb.getCode();
            boolean a=   EstUtils.checkBikeErr(str.getBytes(), 0, str.getBytes().length);
            if (a){
            }else {
                arrayList.add(str);
                bikeVehicleList.add(tb);
            }
        }
        return arrayList;
    }
    /**
     * 批量发卡-修改车辆注册状态
     *
     * @return
     */
    @AutoLog(value = "车辆管理-批量发卡", operateType = 3, logType = 0)
    @ApiOperation(value = "发卡-修改车辆注册状态", notes = "发卡-修改车辆注册状态")
    @DeleteMapping(value = "/updateBikeCode")
    public Result<?> updateBikeCode(@RequestParam(name = "code", required = true) String code) {
        return bikeVehicleService.updateBikeCode(code);
    }

    /**
     * 清卡
     *
     * @param bikeVehicle
     * @return
     */
    @AutoLog(value = "车辆管理-清卡", operateType = 3, logType = 0)
    @ApiOperation(value = "车辆管理-清卡", notes = "车辆管理-清卡")
    @GetMapping(value = "/clearCard")
    public Result<?> clearCard(BikeVehicle bikeVehicle) {
        return bikeVehicleService.clearCard(bikeVehicle);
    }


    /**
     * 换卡
     *
     * @param delCard
     * @return
     */
    @AutoLog(value = "车辆管理-换卡", operateType = 3)
    @ApiOperation(value = "车辆管理-换卡", notes = "车辆管理-换卡")
    @PutMapping(value = "/changeCard")
    public Result<?> changeCard(@RequestBody BikeCard delCard) {
        return bikeVehicleService.changeCard(delCard);
    }

    /**
     * 添加
     *
     * @param bikeVehicle
     * @return
     */
    @ApiOperation(value = "车辆初始化", notes = "车辆初始化")
    @PostMapping(value = "/initialization")
    public Result<?> initialization(@RequestBody BikeVehicleInitialization bikeVehicle) {
        return bikeVehicleService.initialization(bikeVehicle);
    }

    /**
     * 发送短信
     *
     * @param smsParam
     * @return
     */
    @AutoLog(value = "发送短信")
    @ApiOperation(value = "发送短信", notes = "发送短信")
    @PostMapping(value = "/sendMessage")
    public Result<?> sendMessage(@RequestBody SmsParam smsParam) {
        String[] split = smsParam.getPhone().split(",");
        LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String message = null;
        for (String phone : split){
            if (StringUtil.isEmpty(phone) || phone.length() != 11) {
                return Result.error("无效手机号:"+phone);
            }
        }
        for (String phone : split){
            message = SMSDmeo.sendMessage(phone, smsParam.getMessage());
            BikeSysSmsLog bikeSysSmsLog = new BikeSysSmsLog();
            bikeSysSmsLog.setType(smsParam.getType());
            bikeSysSmsLog.setCreateBy(principal.getRealname());
            bikeSysSmsLog.setMobile(phone);
            bikeSysSmsLog.setContent(smsParam.getMessage());
            bikeSysSmsLogService.add(bikeSysSmsLog);
        }
        return Result.OK(message);
    }

    /**
     * 校验车辆code
     *
     * @param code
     * @return
     */
    @ApiOperation(value = "校验车辆code", notes = "校验车辆code")
    @GetMapping(value = "/checkBikeCode")
    public Result<?> checkBikeCode(@RequestParam("code") String code, @RequestParam(value = "id", required = false) String id) {
        QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
        wrapper.eq("code", code);
        if (StringUtils.isNotEmpty(id)) {
            wrapper.ne("id", id);
        }
        List<BikeVehicle> list = bikeVehicleService.list(wrapper);
        if (list.isEmpty()) {
            return Result.OK();
        } else {
            return Result.error("编号已存在");
        }
    }

    /**
     * 编辑
     *
     * @param bikeVehicle
     * @return
     */
    @AutoLog(value = "车辆管理-编辑",operateType = 3)
    @ApiOperation(value = "车辆管理-编辑", notes = "车辆管理-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BikeVehicle bikeVehicle) {
        String code = bikeVehicle.getCode();
        QueryWrapper<BikeVehicle> bikeVehicleQueryWrapper = new QueryWrapper<>();
        bikeVehicleQueryWrapper.eq("code", code);
        bikeVehicleQueryWrapper.ne("id", bikeVehicle.getId());
        List<BikeVehicle> list = bikeVehicleService.list(bikeVehicleQueryWrapper);
        for (BikeVehicle tb : list) {
            if (tb.getCode().equals(bikeVehicle.getCode())) {
                return Result.error("编号重复！");
            }
        }
        bikeVehicleService.updateById(bikeVehicle);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆管理-通过id删除")
    @ApiOperation(value = "车辆管理-通过id删除", notes = "车辆管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        bikeVehicleService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "车辆管理-批量删除")
    @ApiOperation(value = "车辆管理-批量删除", notes = "车辆管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.bikeVehicleService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "车辆管理-通过id查询", notes = "车辆管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BikeVehicle bikeVehicle = bikeVehicleService.getById(id);
        if (bikeVehicle == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(bikeVehicle);
    }

    /**
     * 通过id 校验是否可删
     *
     * @param id
     * @return
     */
    @AutoLog(value = "车辆管理-校验是否可删")
    @ApiOperation(value = "车辆管理-校验是否可删", notes = "车辆管理-校验是否可删")
    @DeleteMapping(value = "/deleteCheck")
    public Result<?> deleteCheck(@RequestParam(name = "id", required = true) String id) {

        return bikeVehicleService.deleteCheck(id);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param bikeVehicle
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BikeVehicle bikeVehicle) {
        return bikeVehicleService.exportXls(request, bikeVehicle);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "车辆管理-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<BikeVehicle> list = ExcelImportUtil.importExcel(file.getInputStream(), BikeVehicle.class, params);
                long start = System.currentTimeMillis();
                // 月月鸟 ： 添加判断覆盖或添加，避免SQLIntegrityConstraintViolationException ID重复覆盖异常
                for (BikeVehicle tb : list) {
                    if (StringUtils.isEmpty(tb.getCode())) {
                        continue;
                    }
                    String code = tb.getCode();
                    QueryWrapper<BikeVehicle> wrapper = new QueryWrapper<>();
                    wrapper.eq("code", code);
                    //if (StringUtils.isNotEmpty(tb.getStationCode())) {
                    //    //获取 pile_id
                    //    tb.setPileId(bikeVehicleService.getPileId(tb));
                    //    if (StringUtils.isNotEmpty(tb.getPileId())) {
                    //        tb.setStatus("1");
                    //    }
                    //}
                    //判断保存还是新增
                    int count = bikeVehicleService.count(wrapper);
                    if (count == 0) {
                        tb.setStatus("3");
                        tb.setIsRegister(BikeConstant.y_n_no);
                        bikeVehicleService.save(tb);
                    } else {

                        bikeVehicleService.update(tb, wrapper);
                    }
                }
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }
}
